/**
 * 
 */
package uk.co.cdal.cobweb.frontend.GUI;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

import uk.co.cdal.cobweb.frontend.Frontend;
import uk.co.cdal.cobweb.frontend.GUI.actionlisteners.AddImageListener;
import uk.co.cdal.cobweb.frontend.GUI.actionlisteners.RemoveImageListener;

/**
 * @author seb
 *
 */
public class ImageDisplay extends JPanel {
	
	private ImageIcon image;
	private Insets emptyMargin = new Insets(0,0,0,0);
	private JFileChooser fc;
	private Frontend frontend = Frontend.getFrontend();
	private SpiderNode container = (SpiderNode)getParent().getParent();

	// When called creates a JPanel with no correspnding content
	public ImageDisplay() {
		fc = new JFileChooser();
		frontend = Frontend.getFrontend();
		container = (SpiderNode) getParent().getParent();
		
		setLayout(new BorderLayout());
		JButton button = new JButton(new ImageIcon("icons/image_add.png"));
		button.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON1) {
					int retval = fc.showOpenDialog(getParent().getParent());
					if(retval == JFileChooser.APPROVE_OPTION) {
						image = new ImageIcon(fc.getSelectedFile().getPath());
						try {
							frontend.getBackend().addImage(image, container.getIdea(), frontend.getBackend().getAddress());
							setImage(image);
						}
						catch(RemoteException re) {
							frontend.getBackend().log.severe("Cannot resolve localhost");
						}
					}
				}
			}
		});
		
		button.setEnabled(true);
		
		button.setToolTipText("Click here to attach a URL");
		button.setOpaque(false);
		button.setIconTextGap(0);
		button.setMargin(emptyMargin);
		button.setContentAreaFilled(false);
		button.setBorderPainted(false);
		button.setFocusPainted(false);
		
		add(button, BorderLayout.EAST);
	}

	// creates a JPanel with a remove button with corresponding content.
	public ImageDisplay(ImageIcon image) {
		
		setLayout(new BorderLayout());
		setImage(image);
		JButton button = new JButton(new ImageIcon("icons/image_delete.png"));
		button.addMouseListener(new RemoveImageListener());
		button.setEnabled(true);
		
		add(button, BorderLayout.EAST);
		add(new JLabel(image), BorderLayout.CENTER);
		
	}

	/**
	 * @return the image
	 */
	public ImageIcon getImage() {
		return image;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(ImageIcon image) {
		this.image = image;
	}
	
}
